<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="代理编号" prop="agentId">
            <el-input
              v-model="queryParams.agentId"
              placeholder="请输入代理编号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="代理等级" prop="agentLevelId">
            <AgentLevelSelect v-model="queryParams.agentLevelId" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button type="primary" @click="openForm('create')">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="ID" align="center" prop="agentId" min-width="80px" />
      <el-table-column label="代理名称" align="left" prop="agentName" min-width="100px">
        <template #default="scope">
          <el-tooltip effect="dark" :content="scope.row.agentName" placement="top">
            <el-text>{{ nameFormat(scope.row.agentName, 6) }}</el-text>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="姓名|昵称" align="left" prop="avatar" min-width="150px">
        <template #default="scope">
          <div class="flex" v-if="scope.row.user">
            <div>
              <el-image
                :preview-teleported="true"
                :src="scope.row.user.avatar"
                class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
              />
            </div>
            <el-tooltip effect="dark" :content="scope.row.user.nickname" placement="top">
              <el-text>{{ nameFormat(scope.row.user.nickname) }}</el-text>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="佣金" align="center" prop="agentPrice" min-width="220px">
        <template #default="scope">
          <div class="flex flex-col">
            <el-text>可用佣金:{{ fenToYuan(scope.row.agentPrice) }}元</el-text>
            <el-text>冻结佣金:{{ fenToYuan(scope.row.frozenPrice) }}元</el-text>
            <el-text>累计佣金:{{ fenToYuan(scope.row.totalPrice) }}元</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="代理等级" align="center" prop="agentLevelName" width="100px" />
      <el-table-column
        label="升级时间"
        align="center"
        prop="agentTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="加入时间"
        align="center"
        prop="agentUserTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="上级代理" align="left" prop="agentParentId" min-width="150px">
        <template #default="scope">
          <div class="flex" v-if="scope.row.agentParentId">
            <el-image
              :preview-teleported="true"
              :src="scope.row.parentUser.avatar"
              class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
            />
            <div class="text-left">
              <div> {{ scope.row.agentParentId }} </div>
              <el-tooltip effect="dark" :content="scope.row.parentUser.nickname" placement="top">
                <el-text>{{ nameFormat(scope.row.parentUser.nickname) }}</el-text>
              </el-tooltip>
            </div>
          </div>
          <div v-else> </div>
        </template>
      </el-table-column>
      <el-table-column
        label="上级代理绑定时间"
        align="center"
        prop="agentParentTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="团队" align="center" prop="brokeragePrice" min-width="180px">
        <template #default>
          <div class="flex flex-col">数量 明细 </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="85">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 0" type="primary">申请中</el-tag>
          <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status == 2" type="info">冻结</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150px" fixed="right">
        <template #default="scope">
          <el-dropdown
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="[
              'trade:brokerage-user:user-query',
              'trade:brokerage-user:order-query',
              'trade:brokerage-user:update-bind-user',
              'trade:brokerage-user:clear-bind-user'
            ]"
          >
            <el-button link type="primary">
              <Icon icon="ep:d-arrow-right" />
              更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <!-- <el-dropdown-item
                  command="openBrokerageUserTable"
                  v-if="checkPermi(['trade:brokerage-user:user-query'])"
                >
                  推广人
                </el-dropdown-item>  -->

                <el-dropdown-item
                  command="openUpdateBindUserForm"
                  v-if="checkPermi(['trade:brokerage-user:update-bind-user'])"
                >
                  修改上级代理
                </el-dropdown-item>
                <el-dropdown-item command="openUpdatePriceForm"> 修改佣金 </el-dropdown-item>
                <el-dropdown-item command="handleUpdateLevel"> 修改等级 </el-dropdown-item>
                <el-dropdown-item
                  command="openBrokerageOrderTable"
                  v-if="checkPermi(['trade:brokerage-user:order-query'])"
                >
                  代理订单
                </el-dropdown-item>
                <el-dropdown-item command="handleFrozenTenant" v-if="scope.row.status != 0">
                  {{ scope.row.status == 1 ? '冻结' : '解冻' }}代理
                </el-dropdown-item>
                <el-dropdown-item command="delete"> 删除代理 </el-dropdown-item>
                <!-- <el-dropdown-item command="openDetails"> 详情 </el-dropdown-item> -->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 修改上级推广人表单 -->
  <UpdateBindUserForm ref="updateBindUserFormRef" @success="getList" />
  <!-- 修改代理佣金 -->
  <DistributorBalanceUpdateForm ref="updatePriceFormRef" @success="getList" />
  <!-- 修改代理等级 -->
  <DistributorLevelUpdateForm ref="updateLevelFormRef" @success="getList" />
  <!-- 推广人列表 -->
  <AgentUserListDialog ref="agentUserListDialogRef" />
  <!-- 推广订单列表 -->
  <AgentOrderListDialog ref="agentOrderListDialogRef" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import * as AgentUserApi from '@/api/mall/trade/agent/user'
import { checkPermi } from '@/utils/permission'
import UpdateBindUserForm from '@/views/mall/trade/agent/distributor/UpdateBindUserForm.vue'
import AgentUserListDialog from '@/views/mall/trade/agent/distributor/AgentUserListDialog.vue'
import AgentOrderListDialog from '@/views/mall/trade/agent/distributor/AgentOrderListDialog.vue'
import AgentLevelSelect from '@/views/mall/trade/agent/level/components/AgentLevelSelect.vue'
import DistributorBalanceUpdateForm from './DistributorBalanceUpdateForm.vue'
import DistributorLevelUpdateForm from './DistributorLevelUpdateForm.vue'
import { nameFormat } from '@/utils/formatter'

import { fenToYuan } from '@/utils'
import { defaultShortcuts } from '@/utils/formatTime'
import { t } from '@/lang'
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
defineOptions({ name: 'TradeBrokerageUser' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  bindUserId: null,
  agentId: undefined,
  agentLevelId: undefined,
  brokerageEnabled: true,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AgentUserApi.getBrokerageUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 添加/修改操作 */
const { push } = useRouter() // 路由跳转

const openForm = (type: string, id?: number) => {
  if (type == 'update') {
    push({ name: 'DistributorUserEdit', params: { id } })
    return
  }
  push({ name: 'DistributorUserAdd' })
}

const handleCommand = (command: string, row: AgentUserApi.AgentUserVO) => {
  switch (command) {
    case 'openBrokerageUserTable':
      openBrokerageUserTable(row.agentId)
      break
    case 'openBrokerageOrderTable':
      openBrokerageOrderTable(row.agentId)
      break
    case 'openUpdateBindUserForm':
      openUpdateBindUserForm(row)
      break
    case 'openUpdatePriceForm':
      openUpdatePriceForm(row.agentId)
      break
    case 'handleUpdateLevel':
      updateLevelFormRef.value.open(row.agentId)
      break
    case 'handleFrozenTenant':
      handleFrozenTenant(row)

      break
    case 'delete':
      handleDelete(row.agentId)
      break
    case 'openDetails':
      openForm('update', row.agentId)
      break
      // case 'handleClearBindUser':
      //   handleClearBindUser(row)
      break
  }
}
/**
 * 修改代理等级
 */
const updateLevelFormRef = ref()
/**
 * 打开代理佣金修改弹框
 */
const updatePriceFormRef = ref()
const openUpdatePriceForm = (id: number) => {
  updatePriceFormRef.value.open(id)
}
/** 打开推广人列表 */
const agentUserListDialogRef = ref()
const openBrokerageUserTable = (id: number) => {
  agentUserListDialogRef.value.open(id)
}

/** 打开推广订单列表 */
const agentOrderListDialogRef = ref()
const openBrokerageOrderTable = (id: number) => {
  agentOrderListDialogRef.value.open(id)
}

/** 打开表单：修改上级推广人 */
const updateBindUserFormRef = ref()
const openUpdateBindUserForm = (row: AgentUserApi.AgentUserVO) => {
  updateBindUserFormRef.value.open(row)
}

const handleFrozenTenant = async (row: AgentUserApi.AgentUserVO) => {
  try {
    let content = `是否冻结代理${row.agentName}`
    let params = {
      agentId: row.agentId,
      remark: ''
    }
    // 删除的二次确认
    await message.delConfirm(content)
    // 发起删除

    await AgentUserApi.updateStatus(params)
    message.success('操作成功')
    // 刷新列表
    await getList()
  } catch {}
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AgentUserApi.deleteAgent(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 清除上级推广人 */
// const handleClearBindUser = async (row: AgentUserApi.AgentUserVO) => {
//   try {
//     // 二次确认
//     await message.confirm(`确认要清除"${row.nickname}"的上级推广人吗？`)
//     // 发起修改
//     await AgentUserApi.clearBindUser({ id: row.agentId })
//     message.success('清除成功')
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 推广资格：开通/关闭 */
// const handleBrokerageEnabledChange = async (row: AgentUserApi.AgentUserVO) => {
//   try {
//     // 二次确认
//     const text = row.brokerageEnabled ? '开通' : '关闭'
//     await message.confirm(`确认要${text}"${row.nickname}"的推广资格吗？`)
//     // 发起修改
//     await AgentUserApi.updateBrokerageEnabled({
//       id: row.agentId,
//       enabled: row.brokerageEnabled
//     })
//     message.success(text + '成功')
//     // 刷新列表
//     await getList()
//   } catch {
//     // 异常时，需要重置回之前的值
//     row.brokerageEnabled = !row.brokerageEnabled
//   }
// }

/** 初始化 **/
onMounted(() => {
  getList()
})
onActivated(() => {
  getList()
})
</script>
